package com.fingard.dsp.bank.directbank.mtcb01;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName MTCB01SinglePay
 * @Author Zhengzy
 * @Date 2019/12/19 9:33
 * @Version 1.0
 **/
public class MTCB01SinglePay extends MTCB01Base implements ISinglePay {
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT TRANSDATE FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        XmlTextWriter xmlTextWriter = new XmlTextWriter();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            // 组装报文 请求头
            MTCB01Header bankHeader = new MTCB01Header();
            bankHeader.trCode = "300001";
            bankHeader.reqNo = p_req1908.reqHeader.reqSeqID;
            bankHeader.fileFlag = "0";// 文件标识 0-报文  1-文件
            // 写入通用头部节点
            writeCommonHeader(xmlTextWriter, bankHeader);
            xmlTextWriter.writeStartElement("body");
            xmlTextWriter.writeElementString("pay_acno", p_req1908.singleDetail.payAct);// 付款账号
            xmlTextWriter.writeElementString("pay_cur_code", convertCurToBank(p_req1908.singleDetail.payCur));// 付款币种
            xmlTextWriter.writeElementString("pay_acname", p_req1908.singleDetail.payName, true);// 付款户名
            xmlTextWriter.writeElementString("as_flag", "0");// 账簿标志 0-不需要 1-需要
            xmlTextWriter.writeElementString("as_acno", "", true);// 账簿号
            xmlTextWriter.writeElementString("as_acname", "", true);// 账簿名称
            xmlTextWriter.writeElementString("pay_accaddr", "", true);// 付款地址
            xmlTextWriter.writeElementString("cert_type", "", true);//凭证种类
            xmlTextWriter.writeElementString("cert_no", p_req1908.singleDetail.askNumber);// 凭证号（企业账务流水号）
            xmlTextWriter.writeElementString("rcv_acno", p_req1908.singleDetail.recAct);// 付款账号
            xmlTextWriter.writeElementString("rcv_cur_code", convertCurToBank(p_req1908.singleDetail.recCur));// 收款币种
            xmlTextWriter.writeElementString("rcv_acname", p_req1908.singleDetail.recName, true);// 收款户名
            xmlTextWriter.writeElementString("rcv_accaddr", p_req1908.singleDetail.recArea, true);// 收款人地址
            xmlTextWriter.writeElementString("rcv_bank_name", p_req1908.singleDetail.recBankName);// 收款行名
            xmlTextWriter.writeElementString("amt", p_req1908.singleDetail.payAmount);// 交易金额
            //Double amt = Double.parseDouble(p_req1908.singleDetail.payAmount);
            xmlTextWriter.writeElementString("bank_flag", "1".equals(p_req1908.singleDetail.sameBnk) ? "0" : "1");// 银行标志 0-本行 1-他行|ats中(1：同行,   0：他行)
            if ("0".equals(p_req1908.singleDetail.sameBnk)) {
                xmlTextWriter.writeElementString("rcv_bank_no", p_req1908.singleDetail.cnapsCode);// 收款行号，收款方账号联行行号
                xmlTextWriter.writeElementString("rcv_bank_name", p_req1908.singleDetail.cnapsName);// 收款行名
            }
            xmlTextWriter.writeElementString("urgency_flag", p_req1908.singleDetail.paySpd);// 加急标志 0-普通 1-加急
            xmlTextWriter.writeElementString("area_flag", "1".equals(p_req1908.singleDetail.sameCity) ? "0" : "1");// 同城异地标志 0-同城 1-异地
            xmlTextWriter.writeElementString("bank_kind", "", true);// 银行类别
            xmlTextWriter.writeElementString("purpose", p_req1908.singleDetail.purpose, true);// 用途 企业转账摘要信息
            xmlTextWriter.writeElementString("postscript", p_req1908.singleDetail.memo, true);// 附言
            xmlTextWriter.writeEndElement();
            xmlTextWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());
           /* String[] tmpStrRet = {"", "<ap>\n" +
                    "\t<head>\n" +
                    "\t\t<tr_code>交易码</tr_code>\n" +
                    "        <cms_corp_no>企业代码</cms_corp_no>\n" +
                    "        <user_no>操作员号</user_no>\n" +
                    "        <org_code>机构号</org_code>\n" +
                    "        <serial_no>交易序号</serial_no>\n" +
                    "        <req_no>发起方序号</req_no>\n" +
                    "        <tr_acdt>交易日期</tr_acdt>\n" +
                    "        <tr_time>交易时间</tr_time>\n" +
                    "        <succ_flag>1</succ_flag>\n" +
                    "        <ret_info>返回信息</ret_info>\n" +
                    "        <ret_code>0000</ret_code>\n" +
                    "        <ext_info>返回扩展信息</ext_info>\n" +
                    "        <file_flag>文件标识</file_flag>\n" +
                    "        <reserved>保留位</reserved>\n" +
                    "\t</head>\n"};*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpsuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");// 成功标识 0成功，其他交易失败。具体看ret_code
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/head/ret_code");// 返回码 0000成功，9999，1102未知，需查证
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");// 返回信息
                    String tmpRetExtInfo = tmpBkReader.getFirstText("/ap/head/ext_info");// 返回附加信息
                    if ("0000".equals(tmpRespCode) && "0".equals(tmpsuccFlag)) {// 执行成功
                        // 存入银行返回的入账日期，用于查询   ats会保存日期 所以不保存也可  查询是以天为单位的  但是为了避免跨天0点前 还是保存日期
                        String transDate = tmpBkReader.getFirstText("/ap/head/tr_acdt");
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, transDate, p_req1908.reqHeader.reqSeqID, p_req1908.reqHeader.reqSeqID});
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetExtInfo);
                        tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        tmpRetAtsDetail.transState = tmpRespCode + tmpsuccFlag;
                        tmpRetAtsDetail.payInfoCode = tmpRespCode + tmpsuccFlag;
                    } else {
                        // 9999，1102未知，需查证
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetExtInfo);
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
        } finally {
            conn.close();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            // 组装报文  报文头
            MTCB01Header bankHeader = new MTCB01Header();
            bankHeader.trCode = "200205";
            bankHeader.reqNo = p_req1944.reqHeader.reqSeqID;
            bankHeader.fileFlag = "0";// 文件标识 0-报文 1-文件
            writeCommonHeader(xmlTextWriter, bankHeader);

            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("cert_no", p_req1944.askNumber));// 企业ERP[账务]流水号
            tmpXElement.addChild(new XElement("req_no", ""));// 企业ERP［请求］流水号
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map.size() == 0) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "没有这条请求的映射流水号！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            tmpXElement.addChild(new XElement("tr_acdt", map.get("TRANSDATE").toString()));
            xmlTextWriter.writeXElement(tmpXElement);
            xmlTextWriter.writeEndElement();
            xmlTextWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());
           /* String[] tmpStrRet = {"", "<ap>\n" +
                    "\t<head>\n" +
                    "\t\t<tr_code>交易码</tr_code>\n" +
                    "        <cms_corp_no>企业代码</cms_corp_no>\n" +
                    "        <user_no>操作员号</user_no>\n" +
                    "        <org_code>机构号</org_code>\n" +
                    "        <serial_no>交易序号</serial_no>\n" +
                    "        <req_no>发起方序号</req_no>\n" +
                    "        <tr_acdt>交易日期</tr_acdt>\n" +
                    "        <tr_time>交易时间</tr_time>\n" +
                    "        <succ_flag>1</succ_flag>\n" +
                    "        <ret_info>返回信息</ret_info>\n" +
                    "        <ret_code>0000</ret_code>\n" +
                    "        <ext_info>返回扩展信息</ext_info>\n" +
                    "        <file_flag>文件标识</file_flag>\n" +
                    "        <reserved>保留位</reserved>\n" +
                    "\t</head>\n" +
                    "\t<body>\n" +
                    "\t   <stat>9</stat>\n" +
                    "\t   <cert_no>流水号</cert_no>\n" +
                    "\t   <req_no>请求号</req_no>\n" +
                    "\t   <serial_no>银企直联流水号</serial_no>\n" +
                    "\t   <error_info>转账说明信息</error_info>\n" +
                    "\t</body>\n" +
                    "</ap>"};*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String tmpRetExtInfo = tmpBkReader.getFirstText("/ap/body/error_info");
                    String tmpsuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    if ("0000".equals(tmpRespCode) && "0".equals(tmpsuccFlag)) {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        String stat = tmpBkReader.getFirstText("/ap/body/stat");
                        tmpRetAtsDetail.transState = stat;// 支付状态码
                        tmpRetAtsDetail.payInfoCode = stat;// 支付信息码
                        tmpRetAtsDetail.respInfo = tmpRetExtInfo != null ? tmpRetExtInfo : "";
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo, tmpRetExtInfo);
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
        } finally {
            conn.close();
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}

